<template>
    <div>
        <el-dialog :title="dialogTitle" :visible.sync="addDialogShow" top="2%" width="800px" :close-on-click-modal="false" :before-close="dialogHandleCancel">
            <el-form v-if="addDialogShow" class="madp-talk-content" ref="form" :model="form" label-width="90px" :rules="rules">
                <el-form-item label="标题:" prop="newsTitle" key="newsTitle">
                    <el-input :disabled="form.onlyRead" maxlength="20" v-model.trim="form.newsTitle" label-width="100%"></el-input>
                </el-form-item>
                <el-form-item label="作者:" prop="newsAuthor" key="newsAuthor">
                    <el-input :disabled="form.onlyRead" maxlength="20" v-model.trim="form.newsAuthor" label-width="100%"></el-input>
                </el-form-item>
                <el-form-item label="来源:" prop="newsAccount" key="newsAccount">
                    <el-input :disabled="form.onlyRead" maxlength="20" v-model.trim="form.newsAccount" label-width="100%"></el-input>
                </el-form-item>
                <el-form-item label="分组:" prop="groupId" key="groupId">
                    <el-cascader :disabled="form.onlyRead" v-model="form.groupId" :options="optionList" :props="defaultProps" clearable></el-cascader>
                </el-form-item>
                <el-form-item label="配图:" prop="newsImg" key="newsImg">
                    <el-upload
                        :disabled="form.onlyRead"
                        v-loading="uploadLoading[1]"
                        :headers="headers"
                        class="avatar-uploader"
                        accept=".jpg, .jpeg, .png, .gif, .bmp"
                        :auto-upload="false"
                        action="#"
                        :show-file-list="false"
                        :on-change="uploadChangeFile1"
                        :file-list="fileList1"
                    >
                        <div v-if="form.newsImg">
                            <img :src="form.newsImg" class="madp-article-cover" />
                        </div>
                        <div v-else>
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                        </div>
                    </el-upload>
                    <p>2M以内(bmp、jpg、png)</p>
                </el-form-item>
                <el-form-item label="音频:" prop="newsContent" key="newsContent">
                    <el-upload
                        :disabled="form.onlyRead"
                        v-loading="uploadLoading[2]"
                        :headers="headers"
                        class="avatar-uploader"
                        :auto-upload="false"
                        action="#"
                        :show-file-list="false"
                        :on-change="uploadChangeFile2"
                        :file-list="fileList2"
                    >
                        <div v-if="form.audioUrl">
                            <video :src="form.audioUrl" controls="controls" class="madp-article-cover" />
                        </div>
                        <div v-if="form.audioUrl && !form.onlyRead">
                            <el-button type="primary">重新上传</el-button>
                        </div>
                        <div v-if="!form.audioUrl">
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                        </div>
                    </el-upload>
                    <p>2M以内</p>
                </el-form-item>
            </el-form>
            <quill-editor
                :disabled="form.onlyRead"
                v-model="form.newsContent"
                class="ql-editor"
                ref="myQuillEditor"
                :options="editorOption"
                @blur="onEditorBlur($event)"
                @focus="onEditorFocus($event)"
                @change="onEditorChange($event)"
                v-loading="quillLoading"
            ></quill-editor>
            <div slot="footer">
                <el-button :type="form.onlyRead ? 'primary' : ''" @click="dialogHandleCancel">{{ form.onlyRead ? '确定' : '取消' }}</el-button>
                <el-button v-if="!form.onlyRead" type="primary" @click="dialogHandleSubmit">确定</el-button>
            </div>
        </el-dialog>
        <el-upload
            ref="uploadRef"
            :headers="headers"
            :show-file-list="false"
            :on-change="uploadChangeFileQuill"
            id="uploadRef"
            accept=".jpg, .jpeg, .png, .gif"
            :auto-upload="false"
            action="#"
        ></el-upload>
    </div>
</template>
<script>
import newsApi from '@/api/store/news.js';
import { quillEditor, Quill } from 'vue-quill-editor';
import ImageResize from '@felrov/quill-image-resize-module';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { sysFileUpload } from '@/api/customer-into/marketing-material';
import store from '@/store';
const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
    ['blockquote', 'code-block'], // 引用  代码块
    [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
    [{ script: 'sub' }, { script: 'super' }], // 上标/下标
    [{ indent: '-1' }, { indent: '+1' }], // 缩进
    [{ direction: 'rtl' }], // 文本方向
    [{ size: ['10px', '12px', '14px', '16px', '18px', '20px', '24px', '28px', '32px', '36px', false] }], // 字体大小，false设置自定义大小
    [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
    [{ align: [] }], // 对齐方式
    ['link', 'image'],
    ['clean'] // 清除文本格式
];
// 自定义字体大小
let Size = Quill.import('attributors/style/size');
Size.whitelist = ['10px', '12px', '14px', '16px', '18px', '20px', '24px', '28px', '32px', '36px', false];
Quill.register(Size, true);
Quill.register('modules/imageResize', ImageResize);
export default {
    components: {
        quillEditor
    },
    props: {
        propsForm: {
            type: Object,
            default: () => {
                return {};
            }
        },
        addDialogShow: {
            type: Boolean
        },
        dialogTitle: {
            type: String
        },
        dialogType: {
            type: String
        },
        // 分组下拉框数据
        options: {
            type: Array,
            default: () => {
                return [];
            }
        }
    },
    data() {
        return {
            // 表单校验规则
            rules: {
                newsTitle: [
                    {
                        required: true,
                        message: '请输入标题',
                        trigger: 'blur'
                    }
                ],
                newsAuthor: [
                    {
                        required: true,
                        message: '请输入作者',
                        trigger: 'blur'
                    }
                ],
                newsAccount: [
                    {
                        required: true,
                        message: '请输入来源',
                        trigger: 'blur'
                    }
                ],
                groupId: [
                    {
                        required: true,
                        message: '请选择分组',
                        trigger: 'change'
                    }
                ]
            },
            // 新增表单
            form: {},
            // 下拉框props
            defaultProps: {
                checkStrictly: false,
                value: 'groupId',
                label: 'groupName'
            },
            // 上传loading
            uploadLoading: {},
            // 富文本内容
            content: '',
            // 富文本配置项
            editorOption: {
                placeholder: '请填写文章内容',
                modules: {
                    //工具栏定义的
                    toolbar: {
                        container: toolbarOptions, // 工具栏
                        handlers: {
                            image: (value) => {
                                if (value) {
                                    // 在编辑器中点击图片 icon 会触发此事件
                                    this.$refs.uploadRef.$children[0].$refs.input.click();
                                }
                            }
                        }
                    },
                    imageResize: {
                        displayStyles: {
                            backgroundColor: 'black',
                            border: 'none',
                            color: 'white'
                        },
                        modules: ['Resize', 'DisplaySize', 'Toolbar']
                    }
                }
            },
            // 富文本loading
            quillLoading: false,
            // 请求头
            headers: {
                Authorization: 'Bearer ' + store.getters.access_token,
                LdapToken: store.getters.ldap_token
            },
            // 文件列表
            fileList1: [],
            fileList2: [],
            // 分组列表
            optionList: []
        };
    },
    watch: {
        addDialogShow: {
            handler(val) {
                if (val) {
                    this.initForm();
                }
            }
        }
    },
    computed: {
        editor() {
            return this.$refs.myQuillEditor.quill;
        }
    },
    methods: {
        // 初始化表单数据
        initForm() {
            this.optionList = this.options.filter((i) => {
                return i.system == false;
            });
            let obj = JSON.parse(JSON.stringify(this.propsForm));
            if (obj.type) {
                let callback = this.reduceArr(this.optionList, obj.type);
                obj.groupId = callback;
            }
            this.form = obj;
        },
        // 处理id
        reduceArr(data, id) {
            if (data instanceof Array) {
                for (let i = 0; i < data.length; i++) {
                    let callback = this.reduceArr(data[i], id);
                    if (callback) return callback;
                }
            } else {
                if (data.children) {
                    let callback = this.reduceArr(data.children, id);
                    if (callback && callback instanceof Array) {
                        return [data.groupId, ...callback];
                    }
                } else {
                    if (data.groupId === id) return [data.groupId];
                }
            }
        },
        // 弹窗点击取消
        dialogHandleCancel() {
            this.$emit('dialogHandleCancel');
        },
        // 弹窗点击确定
        dialogHandleSubmit() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    let obj = JSON.parse(JSON.stringify(this.form));
                    obj.groupId = obj.groupId.pop();
                    if (obj.newsKey) {
                        newsApi.editNews(obj).then((res) => {
                            if (res.data.code != 0) return;
                            this.$message.success('编辑成功!', 1);
                            this.$emit('handleUpdate');
                        });
                    } else {
                        newsApi.addNews(obj).then((res) => {
                            if (res.data.code != 0) return;
                            this.$message.success('新增成功!', 1);
                            this.$emit('handleUpdate');
                        });
                    }
                }
            });
        },
        // 文件上传
        uploadChangeFileQuill(file) {
            if (file && file.raw) {
                let fileMsg = file.raw;
                if (fileMsg.size / 1024 / 1024 > 2) {
                    this.$message.error('上传不能超过2M');
                    return;
                }
                let fd = new FormData();
                fd.append('file', file.raw);
                this.quillLoading = true;
                sysFileUpload(fd)
                    .then((res) => {
                        if (res.data.code === 0) {
                            let url = res.data.data.url;
                            let quill = this.editor;
                            // 如果上传成功, 获取光标所在位置, 插入图片，res 为服务器返回的图片链接地址
                            if (res) {
                                let length = quill.getSelection().index;
                                quill.insertEmbed(length, 'image', url);
                                // 调整光标到最后
                                quill.setSelection(length + 1);
                            }
                        }
                        this.quillLoading = false;
                    })
                    .catch(() => {
                        this.quillLoading = false;
                    });
            }
        },
        onEditorBlur() {}, // 失去焦点事件
        onEditorFocus() {}, // 获得焦点事件
        onEditorChange() {}, // 内容改变事件
        // 上传事件
        uploadChangeFile1(file) {
            if (file && file.raw) {
                let fileMsg = file.raw;
                if (fileMsg.size / 1024 / 1024 > 2) {
                    this.fileList1 = [];
                    this.$message.error('上传不能超过2M');
                    return;
                }
                this.sysFileUploadFn(file, 'newsImg', 1);
            }
        },
        // 上传事件
        uploadChangeFile2(file) {
            if (file && file.raw) {
                let fileMsg = file.raw;
                if (fileMsg.size / 1024 / 1024 > 2) {
                    this.fileList2 = [];
                    this.$message.error('上传不能超过2M');
                    return;
                }
                this.sysFileUploadFn(file, 'audioUrl', 2);
            }
        },
        // 文件上传
        sysFileUploadFn(file, key, val) {
            let fd = new FormData();
            fd.append('file', file.raw);
            this.uploadLoading[val] = true;
            sysFileUpload(fd)
                .then((res) => {
                    if (res.data.code === 0) {
                        let fileMsg = res.data.data;
                        this.form[key] = fileMsg.url;
                    }
                    delete this.uploadLoading[val];
                    this.$forceUpdate();
                })
                .catch(() => {
                    delete this.uploadLoading[val];
                });
        }
    }
};
</script>
<style scoped lang="scss">
.avatar-uploader {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 200px;
    height: 200px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    .madp-article-cover {
        object-fit: contain;
        width: 100%;
        width: 100%;
    }
}
/deep/.ql-editor {
    min-height: 200px;
}
.avatar-uploader-icon {
    font-size: 28px !important;
    color: #8c939d !important;
    width: 178px !important;
    height: 178px !important;
    line-height: 178px !important;
    text-align: center !important;
}
/*字体样式*/
/*//默认的样式*/
.ql-container {
    font-size: 14px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='10px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='10px']::before {
    content: '10px';
    font-size: 10px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='12px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='12px']::before {
    content: '12px';
    font-size: 12px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='14px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='14px']::before {
    content: '14px';
    font-size: 14px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='16px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='16px']::before {
    content: '16px';
    font-size: 16px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='18px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='18px']::before {
    content: '18px';
    font-size: 18px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='20px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='20px']::before {
    content: '20px';
    font-size: 20px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='24px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='24px']::before {
    content: '24px';
    font-size: 24px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='28px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='28px']::before {
    content: '28px';
    font-size: 28px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='32px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='32px']::before {
    content: '32px';
    font-size: 32px;
}
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='36px']::before,
/deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='36px']::before {
    content: '36px';
    font-size: 36px;
}
</style>
